import os

from transformers.models.auto.modeling_auto import AutoModelForCausalLM

from transformers import AutoModelForCausalLM, AutoTokenizer

model_dir = os.path.join('D:', os.path.sep, 'ModelSpace', 'Qwen2.5', 'Qwen2.5-1.5B-Instruct')
model = AutoModelForCausalLM.from_pretrained(
    model_dir,
    torch_dtype="auto",
    device_map="auto",
    local_files_only=True,
)
print(model)

tokenizer = AutoTokenizer.from_pretrained(
    model_dir,
    local_files_only=True,
)

prompt = '你是谁？'
messages = [
    {'role': 'system', 'content': '你是老牛同学的AI助手，你总是给老牛同学非常有用的帮助。'},
    {'role': 'user', 'content': prompt}
]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
)
model_inputs = tokenizer(
    [text],
    return_tensors='pt',
).to(model.device)

print(f'开始推理: {prompt}')

generated_ids = model.generate(
    **model_inputs,
    max_new_tokens=512,
)

print('推理完成.')

generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]

response = tokenizer.batch_decode(
    generated_ids,
    skip_special_tokens=True,
)[0]

print(f'推理结果: {response}')
